<template>
  <div class="app">
    <el-card class="box-card">
      <h2>用户登录</h2>
      <el-form
        :model="state.loginFrom"
        :rules="state.loginRules"
        ref="login"
        status-icon
        label-width="20px"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="state.loginFrom.username"
            :prefix-icon="Avatar"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Unlock"
            type="password"
            autocomplete="off"
            v-model="state.loginFrom.password"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            color="#626aef"
            style="color: white"
            type="primary"
            @click="setLogin"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script  setup>
import { reactive, toRefs, computed, watch, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getLogin } from "@/http/api.js";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import md5 from "md5";

const router = useRouter();
const store = useStore();
const state = reactive({
  loginFrom: {
    username: "super-admin",
    password: "123456",
  },
  loginRules: {
    username: [
      {
        required: true,
        message: "请输入用户账户",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        min: 6,
        max: 16,
        message: "请输入账户密码 6-16位",
        trigger: "blur",
      },
    ],
  },
});

const login = ref();
const setLogin = () => {
  getLogin({
    ...state.loginFrom,
    password: md5(state.loginFrom.password),
  }).then((res) => {
    console.log("登录成功", res);
    if (res.code == 200) {
      ElMessage.success(res.message);
      store.dispatch("addToken", res.data.token);
      store.commit("addName", state.loginFrom.username);
      router.push("/profile");
    }
  });
};
</script>

<style scoped lang='scss'>
.app {
  width: 100%;
  height: 100%;
  background-color: #2c3e50;
  .box-card {
    width: 500px;
    padding: 20px;
    height: 342px;
    position: relative;
    left: 50%;
    transform: translate(-50%, 50%);

    .el-form-item {
      padding: 5px 0px;
      text-align: right;

      .el-button {
        width: 100%;
        display: block;
      }
    }
  }
}
</style>
